package com.module.overview.ui.schedule.provider

import android.graphics.Typeface
import android.util.Log
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.home.ScoringFactorsModel
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.data.repository.HomeApi
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.formatTimeByBean
import com.common.base.app.extras.setSafeOnClickListener
import com.common.base.app.extras.setVisible
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.common.app.widget.AnimatedRoundProgressBar
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.groupSleepDataByQualityAndTime
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/6/16
 *
 * 描述：睡眠卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvMainSleepCardProvider(
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP,
    override val layoutId: Int = R.layout.overview_main_sleep_crad_provider
) : BaseItemProvider<CardSettingModel>() {

    private var requestJob: Job? = null
    var scope = CoroutineScope(Dispatchers.IO)

    var tvOverallScoring: TextView? = null
    var rpdSleep: AnimatedRoundProgressBar? = null

    init {

    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvOverallScoring = viewHolder.getView(R.id.tvOverallScoring)
        rpdSleep = viewHolder.getView(R.id.rpdSleep)
        super.onViewHolderCreated(viewHolder, viewType)
    }


    override fun convert(helper: BaseViewHolder, item: CardSettingModel) {

        helper.getView<View>(R.id.totalSleepCard).setSafeOnClickListener {
//            UserHelper.checkLogin().yes {
//            }
            RouterHelper.navigationPostcard(RouterHub.ROUTER_OVERVIEW_CARD_HISTORY_DETAILS)
                .withString(KeyBundle.BUNDLE_TITLE, getString(R.string.common_sleep_hint))
                .navigation()
        }

        helper.itemView.setVisible(item.isEnabled)

        doOnIOThread {
            val timeTemp = TimeUtils.getTimeRangeForSleep(TimeUtils.getTimeDateLong())
            SleepInfoRepo.instance.findByTimeRangeByNight(timeTemp.first, timeTemp.second)?.let { listIt->
                listIt.sortedBy { it.createdTime }//按时间排序（升序）
                var totalDuration = 0L//睡眠总时长，单位：分钟

                if (listIt.isNotEmpty()) {
                    val groupedSleepData = groupSleepDataByQualityAndTime(listIt)
                    groupedSleepData.forEach {sleepDataIt-> // 睡眠质量 0,清醒(离床) 1:快速眼动 2:浅睡 3:深睡 4:未佩戴  101:小睡（自用） -999：未知（自用）
                        totalDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                    }
                }
                formatTimeByBean(totalDuration*60*1000).run{
                    doOnUiThread {
                        SpanUtils.create()
                            .addForeColorSection(
                                this.hours.toString(),
                                ViewUtils.getColor(R.color.c_191919)
                            )
                            .setAbsSize(this.hours.toString(), 16)
                            .setStyle(this.hours.toString(), Typeface.BOLD)
                            .addSection(getString(R.string.common_hours_hint))
                            .addForeColorSection(
                                this.minutes.toString(),
                                ViewUtils.getColor(R.color.c_191919)
                            )
                            .setAbsSize(this.minutes.toString(), 16)
                            .setStyle(this.minutes.toString(), Typeface.BOLD)
                            .addSection(getString(R.string.common_minutes_hint)) //添加普通字符串
                            .showIn(helper.getView(R.id.tvSleepDuration))
                    }
                }
            }
        }
    }

    private fun getSleepScoringFactors() {
        tvOverallScoring?.text = getString(R.string.common_rail_unit)

        // 取消之前的请求
        requestJob?.cancel()

        requestJob = scope.launch {
            RxHttp.postJson(HomeApi.GET_SLEEP_SCORING_FACTORS)
                .add("date", TimeUtils.getYearMonthDay(TimeUtils.getTimeDateLong()))
                .toFlow<CommonBean<ScoringFactorsModel>>()
                .catch { e ->
                    // 处理异常
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                                tvOverallScoring?.text = dataIt.total_score.toInt().toString()
                                rpdSleep?.setProgressWithAnimation(dataIt.total_score.toInt())
                            }
                        }
                    }
                }
        }
    }
}